<?php

namespace app\api\controller;

use addons\epay\library\QRCode;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;
use addons\epay\library\Service;
use fast\Random;
use think\addons\Controller;
use think\Config;
use think\Request;
use addons\third\model\Third;
use think\Exception;
use Yansongda\Pay\Pay;
/**
 * 店铺接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['shopcategory','shoplist','mycontent','merchanthomepage','shopdetails',"actionsend",'hxdiscount','ground','qrCode'];
    protected $noNeedRight = ['*'];

    /**
     * 店铺分类
     *
     */
    public function shopcategory()
    {
        $cate = Db::name('cate')->order('weight desc,id desc')->field('id,title')->select();
        
        $this->success('请求成功',$cate);
    }
    
        /**
     * 计算距离
     * @param  Decimal $lat1 起点纬度
     * @param  Decimal $lng1  起点经度
     * @param  Decimal $lat2 终点纬度 
     * @param  Decimal $lng2  终点经度
     */
    public function getDistance($lat1, $lng1, $lat2, $lng2){ 
        $earthRadius = 6367000; //近似地球半径（米）
        $lat1 = ($lat1 * pi() ) / 180; 
        $lng1 = ($lng1 * pi() ) / 180; 
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180; 
        $calcLongitude = $lng2 - $lng1;     //长度
        $calcLatitude = $lat2 - $lat1;      //纬度
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
        $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
        $Distance = $earthRadius * $stepTwo; 
        
        if ($Distance >= 1000) {
            $Distance = round($Distance/1000,2);
            return $Distance . 'km';
        }
    
        return round($Distance) . 'm'; 
    }
    
    //店铺列表
    public function shoplist()
    {
        $q = $this->request->post('q','');
        $cate_id = $this->request->post('cate_id','');
        $lng = $this->request->post('lng','');
        $lat = $this->request->post('lat','');
        
        $where['status'] = array('eq','normal');
        if(!empty($q))
        {
            $where['shop_name'] = array('like','%'.$q.'%');
        }
        if(!empty($cate_id))
        {
            $where['cate_id'] = array('eq',$cate_id);
        }
        // var_dump($where);exit;
        
        $shoplist = Db::name('shop')
        ->where($where)
        ->order('id desc')
        ->field('id,shop_name,label_ids,discount,lng,lat,logo')
        ->select();
        $config = get_addon_config('alioss');
        foreach ($shoplist as $k=>$v) {
            if(!empty($lng) && !empty($lat))
            {
                $shoplist[$k]['distance'] = $this->getDistance($lat,$lng,$v['lat'],$v['lng']);
            }
            $shoplist[$k]['logo'] = $config['cdnurl'].$v['logo'];
                // var_dump($v['label_ids']);exit;
           $label =  Db::name('label')->where('id','in',$v['label_ids'])->select();
          
           if(!empty($label))
           {
               $str = '';
               foreach ($label as $k1=>$v1) {
                  $str.=$v1['name'].',';
               }
               $shoplist[$k]['label'] = substr_replace($str ,"",-1);
           }
          
        }
        
        $this->success('请求成功',$shoplist);
    }
    
    
    //店铺详情
    public function shopdetails()
    {
        $shop_id = $this->request->post('shop_id','');
        if(!$shop_id)
        {
            $this->error('参数错误');
        }
        $config = get_addon_config('alioss');
        $shop = Db::name('shop')->where('id',$shop_id)->find();
        $str = '';
        if(!empty($shop['shop_images'])) {
            $im = explode(',', $shop['shop_images']);

            foreach ($im as $k=>$v){
                if($k == 0){
                    $str .= $config['cdnurl'] . $v;
                }else{
                    $str .= ',' . $config['cdnurl'] . $v;
                }

            }
            $shop['shop_images'] = $str;
        }
        $shop['logo'] = $config['cdnurl'].$shop['logo'];
        if(!empty($shop['label_ids']))
        {
           $label =  Db::name('label')->where('id','in',$shop['label_ids'])->select();
          
           if(!empty($label))
           {
               $str = '';
               foreach ($label as $k1=>$v1) {
                  $str.=$v1['name'].',';
               }
               $shop['label'] = substr_replace($str ,"",-1);
           }
        }
        
        $goods = Db::name('goods')->where('shop_id',$shop_id)->find();

        if(!empty($goods))
        {
            $goods['image'] = $config['cdnurl'].$goods['image'];
            $shop['goods_arr'] = $goods;
        }
        
        Db::name('goods')->where('shop_id',$shop_id)->order('id desc')->setInc('view',1);
        $collection = Db::name('collection')->where(['user_id'=>$this->auth->id,'shop_id'=>$shop_id])->find();
        if(!empty($collection))
        {
            $shop['is_collection'] = 1;
        }else{
            $shop['is_collection'] = 0;
        }
        
        $dq = date('H:i',time());
        if(strtotime($dq) >strtotime($shop['business_times']) && strtotime($dq)<strtotime($shop['endtime']))
        {
            $shop['business'] = '营业中:'.$shop['business_times'].'~'.$shop['endtime'];
        }else{
            $shop['business'] = '休息中:'.$shop['business_times'].'~'.$shop['endtime'];
        }
        $shxdiscount = Db::name('hxdiscount')->where(['shop_id'=>$shop_id])->order("duration asc")->find();
        $nhxdiscount = Db::name('hxdiscount')->where(['shop_id'=>$shop_id])->order("duration desc")->find();
        $shop['wenan'] = '购买商品核销后送'.floatval($shxdiscount['duration'])."~".floatval($nhxdiscount['duration']).'小时充电时长';
        
        $this->success('请求成功',$shop);
    }
    
    //收藏
    public function collection()
    {
       $shop_id = $this->request->post('shop_id','');
       if(!$shop_id)
       {
         $this->error('参数错误');
       }
       $collection = Db::name('collection')->insert(['shop_id'=>$shop_id,'user_id'=>$this->auth->id,'createtime'=>time()]);
       if($collection != false)
       {
            $this->success('收藏成功');
       }else{
            $this->error('收藏失败');
       }
    }
    //取消收藏
    public function nocollection()
    {
        $shop_id = $this->request->post('shop_id','');
        if(!$shop_id)
       {
         $this->error('参数错误');
       }
       $collection = Db::name('collection')->where('id',$shop_id)->delete();
       if($collection != false)
       {
            $this->success('取消成功');
       }else{
            $this->error('取消失败');
       }
    }
    
    //收藏列表
    public function collectionlist()
    {
        $user_id = $this->request->post('user_id','');
        $collection= Db::name('collection')
                    ->alias('a')
                    ->join('shop s','a.shop_id = s.id')
                    ->order('a.id desc')
                    ->where('a.user_id',$user_id)
                    ->field('a.id,s.shop_name,s.logo,s.label_ids,s.discount')
                    ->select();
        $config = get_addon_config('alioss');
        foreach ($collection as $k=>$v) {
            $collection[$k]['logo'] = $config['cdnurl'].$v['logo'];
             if(!empty($v['label_ids']))
            {
               $label =  Db::name('label')->where('id','in',$v['label_ids'])->select();
              
               if(!empty($label))
               {
                   $str = '';
                   foreach ($label as $k1=>$v1) {
                      $str.=$v1['name'].',';
                   }
                   $collection[$k]['label'] = substr_replace($str ,"",-1);
               }
            }
        }           
       
        // var_dump($collection);exit;
        $this->success('请求成功',$collection);
    }
    
    //提交订单
    public function orderpay()
    {
        $amount = $this->request->post('amount');
        $type = $this->request->post('type','wechat');
        $method = $this->request->post('method');
        $goods_id = $this->request->post('goods_id');
        $shop_id = $this->request->post('shop_id');
       
        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }
        //  var_dump($amount);exit;
        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }
        
        $shop = Db::name('shop')->where('id',$shop_id)->find();
        $order = Db::name('order')->where('shop_id',$shop_id)->count();
        if($shop['buy_num'] >0)
        {
            if($order >= $shop['buy_num'])
            {
                $this->error("限购".$shop['buy_num'].'次');
            }
        }
        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        
         $info = get_addon_info('third');
            if (!$info || !$info['state']) {
                $this->error("请在后台安装第三方登录插件");
            }
            /*$third = Third::where('platform', 'wechat')
                // ->where('apptype', $method)
                ->where('user_id', $this->auth->id)
                ->find();

        if (!$third) {
            $this->error("未找到微信授权的用户信息", 'bind');
        }
        $openid = $third['openid'];*/
        ////
        $shop = Db::name('user')->where('id',$this->auth->id)->find();
        if (!$shop['openid']) {
            $this->error("未找到微信授权的用户信息");
        }
        $openid = $shop['openid'];
        ///
        
        $params = [
            'amount'=>$amount,
            'orderid'=>$out_trade_no,
            'type'=>"wechat",
            'title'=>"订单支付",
            'notifyurl'=>$notifyurl,
            'returnurl'=>$returnurl,
            'method'=>"miniapp",
            'openid'=>$openid,
        ];
        try {
            $response=Service::submitOrder($amount, $out_trade_no, 'wechat', "订单支付", $notifyurl, $returnurl,'miniapp',$openid);
                //$response = Service::submitOrder($params);
                if($response)
                {
                    $goods = Db::name('goods')->where('id',$goods_id)->find();
                    $data = ['goods_id'=>$goods_id,'order_sn'=>$out_trade_no,'user_id'=>$this->auth->id,'goods_name'=>$goods['name'],'goods_image'=>$goods['image'],'price'=>$amount,'memo'=>$method,'createtime'=>time(),'shop_id'=>$shop_id];
                    Db::name('order')->insert($data);
                }
            } catch (GatewayException $e) {
                throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
            }
        
        $this->success('请求成功',$response);
       
    }
    
    //我的订单
    public function myorder()
    {
        $user_id = $this->request->post('user_id','');
        
        $order = Db::name('order')
                    ->alias('a')
                    ->join('shop s','s.id = a.shop_id')
                    ->where(['a.user_id'=>$user_id,'a.paystate'=>1])
                    ->order('a.id desc')
                    ->field('a.id,a.order_sn,a.orderstate,a.goods_name,a.goods_image,a.price,s.shop_name')
                    ->select();
        if(!empty($order))
        {
            $request = Request::instance();
            $domain = $request->domain();
            $config = get_addon_config('alioss');
            foreach ($order as $k=>$v) {

                $order[$k]['goods_image'] = $config['cdnurl'] . $v['goods_image'];
                $qrCode    = build($v['order_sn']);
                $qrCodeUrl =  serverUrl().'/assets/img/'.$qrCode;
               $order[$k]['qrcode'] = $qrCodeUrl;
               //$order[$k]['qrcode'] = $domain."/qrcode/build?text=".$v['order_sn'];
              // $order[$k]['qrcode'] = "http://youpin-img.oss-cn-shenzhen.aliyuncs.com/uploads/20220322/b4937e3ff047142facd6477d70d351f7.jpg";
            }
            //$order[$k]['goods_image'] = "http://youpin-img.oss-cn-shenzhen.aliyuncs.com/uploads/20220322/b4937e3ff047142facd6477d70d351f7.jpg";
        }
                    
        $this->success('请求成功',$order);
    }
    //取消订单
    public function cancelorder()
    {
        
        $order_sn = $this->request->post('order_sn','');
        if(!$order_sn)
        {
            $this->error('参数错误');
        }
             
        $info = get_addon_info('epay');
        if (!$info || !$info['state']) {
           
            $this->error(__('请在插件市场安装微信支付宝整合插件并启用'));
        }
        $order = Db::name('order')->where('order_sn',$order_sn)->find();
        if($order['orderstate'] ==3)
        {
            $this->error('非法操作');
        }
        // if ($order['price'] < 0.1) {
        //     $this->error(__('最终提现金额最少0.1元'));
        // }
         $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
         $user = Db::name('user')->where('id',$order['user_id'])->find();
        //  var_dump($third['openid']);exit;
            try {
                $order = [
                    'partner_trade_no' => $out_trade_no,
                    'openid' => $user['openid'],
                    'check_name' => 'NO_CHECK',
                    'amount' => $order['price']*100,
                    'desc' => "取消订单"
                ];
                
                $config = Service::getConfig('wechat');
               
                $result = Pay::wechat($config)->transfer($order);
           
                if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                     Db::name('order')->where('order_sn',$order_sn)->update(['orderstate'=>2]);
                     $this->success('取消成功');
                    //转账成功逻辑
                } else {
                    $this->error(__('转账失败！'));
                }
            } catch (\Exception $e) {
                $this->error(__($e));
               
            }
        $this->error(__('取消失败！'));
    }
    
    //关于我们
    public function mycontent()
    {
        //$re_data1['img'] = "http://youpin-img.oss-cn-shenzhen.aliyuncs.com/uploads/20220322/b4937e3ff047142facd6477d70d351f7.jpg";
        $re_data2[0]['name'] = "公司介绍";
        $re_data2[1]['name'] = "业务介绍";
        $re_data2[2]['name'] = "关注我们";
        $re_data2[0]['mycontent'] = Config::get('site.mycontent');
        $re_data2[1]['mycontent'] = Config::get('site.mycontent_1');
        $re_data2[2]['mycontent'] = Config::get('site.mycontent_2');
        $re_data['img'] = Config::get('site.mycontent_img');
        $re_data['list'] = $re_data2;
        $this->success('请求成功',$re_data);
    }
    
    public function userinfo()
    {
        $user = Db::name('user')->where('id',$this->auth->id)->field('id,username,avatar,shop_id')->find();
        $third = Db::name('third')->where('user_id',$this->auth->id)->find();
        if(!empty($third))
        {
            $user['is_bd'] = 1;
        }else{
            $user['is_bd'] = 0;
        }
        $user['kefu_mobile'] = Config::get('site.mobile');
        $this->success('请求成功',$user);
    }
    //商家主页
    public function merchanthomepage()
    {
        // $this->auth->id = 12;
        $shop_id = $this->request->post('shop_id');
        
        $user= Db::name('user')->where('id',$this->auth->id)->find();
         if($user['shop_id'] == 0)
        {
            $this->error('请您先绑定店铺');
        }
        $config = get_addon_config('alioss');
        $shop = Db::name('shop')->where('id',$shop_id)->field('id,shop_name,logo,label_ids,phone')->find();
        $shop['logo'] = str_replace($config['cdnurl'],"",$shop['logo']);
       // $shop['logo'] = $config['cdnurl'] . $shop['logo'];
         if(!empty($shop['label_ids']))
        {
           $label =  Db::name('label')->where('id','in',$shop['label_ids'])->select();
          
           if(!empty($label))
           {
               $str = '';
               foreach ($label as $k1=>$v1) {
                  $str.=$v1['name'].',';
               }
               $shop['label'] = substr_replace($str ,"",-1);
               $config = get_addon_config('alioss');
               $shop['logo'] = $config['cdnurl'] . $shop['logo'];
           }
        }
        $writeoff_log = Db::name('writeoff_log')
                                ->alias('a')
                                ->join('user u','a.user_id = u.id')
                                ->join('shop s','a.shop_id = s.id')
                                ->where('a.writeoff_id',$this->auth->id)
                                ->field('s.shop_name,u.avatar,a.goods_name,a.market_price,a.price,a.goods_image')
                                ->order('a.id desc')
                                ->select();
         foreach ($writeoff_log as $k=>$v){
             $writeoff_log[$k]['goods_image'] = $config['cdnurl'] . $v['goods_image'];
        }
        $writeoff_num = Db::name('writeoff_log')->where('writeoff_id',$this->auth->id)->count();                       
        $shop['writeoff_num'] = $writeoff_num;
        $shop['writeoff_list'] = $writeoff_log;
        $this->success('请求成功',$shop);
    }
    
    //编辑店铺
    public function editshop()
    {
        $shop_id = $this->request->post('shop_id','');
        $shop_name = $this->request->post('shop_name','');
        $phone = $this->request->post('phone','');
        $shop_address = $this->request->post('shop_address','');
        $business_times = $this->request->post('business_times','');
        $endtime = $this->request->post('endtime','');
        $shop_images = $this->request->post('shop_images','');
        $label_ids = $this->request->post('label_ids','');
        
        if($this->request->isPost()) {
           $data=[];
            $config = get_addon_config('alioss');
           if(!empty($shop_name))
           {
               $data['shop_name'] = $shop_name;
           }
            if(!empty($phone))
           {
               $data['phone'] = $phone;
           }
            if(!empty($shop_address))
           {
               $data['shop_address'] = $shop_address;
           }
            if(!empty($business_times))
           {
               $data['business_times'] = $business_times;
           }
            if(!empty($shop_images))
           {
               $shop_images = str_replace($config['cdnurl'],"",$shop_images);
               $data['shop_images'] = $shop_images;
           }
            if(!empty($label_ids))
           {
               $data['label_ids'] = $label_ids;
           }
            if(!empty($endtime))
           {
               $data['endtime'] = $endtime;
           }
           Db::name('shop')->where('id',$shop_id)->update($data);
           $this->success('编辑成功');
        }
        
       $shop = Db::name('shop')->where('id',$shop_id)->field('id,shop_name,phone,shop_address,business_times,label_ids,shop_images,endtime')->find();
        $this->success('请求成功',$shop);
    }
    
    //添加自定义标签
    public function addlabel()
    {
        $label = $this->request->post('label','');
        
        $labels = Db::name('label')->insertGetId(['name'=>$label,'createtime'=>time()]);
        $data['label_ids'] = $labels;
        $data['label'] = $label;
        $this->success('请求成功',$data);
    }
    /**
     * @return void
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 订单详情
     */
    public function orderdetails(){
        $order_sn = $this->request->post('order_sn','');
        if(!$order_sn)
        {
            $this->error('参数错误');
        }
        $order = Db::name('order')->where('order_sn',$order_sn)->find();
        $shop_id = $order['shop_id'];

        $config = get_addon_config('alioss');
        $shop = Db::name('shop')->where('id',$shop_id)->find();
        $str = '';
        if(!empty($shop['shop_images'])) {
            $im = explode(',', $shop['shop_images']);

            foreach ($im as $k=>$v){
                if($k == 0){
                    $str .= $config['cdnurl'] . $v;
                }else{
                    $str .= ',' . $config['cdnurl'] . $v;
                }

            }
            $shop['shop_images'] = $str;
        }
        $shop['logo'] = $config['cdnurl'].$shop['logo'];
        if(!empty($shop['label_ids']))
        {
            $label =  Db::name('label')->where('id','in',$shop['label_ids'])->select();

            if(!empty($label))
            {
                $str = '';
                foreach ($label as $k1=>$v1) {
                    $str.=$v1['name'].',';
                }
                $shop['label'] = substr_replace($str ,"",-1);
            }
        }

        $goods = Db::name('goods')->where('shop_id',$shop_id)->find();

        if(!empty($goods))
        {
            $goods['image'] = $config['cdnurl'].$goods['image'];
            $shop['goods_arr'] = $goods;
        }
        $shop['order_time'] = date('Y-m-d H:i:s',$order['createtime']);
        $shop['order_sn'] = $order['order_sn'];
        $this->success('请求成功',$shop);
    }
    //核销
    public function scancode()
    {
        $order_sn = $this->request->post('order_sn','');
        $hxdiscount_id = $this->request->post('hxdiscount_id',0);

        if(!$order_sn)
        {
            $this->error('参数有误');
        }
        $user = Db::name('user')->where('id',$this->auth->id)->find();
        if($user['shop_id'] ==0)
        {
            $this->error('请您先申请核销员身份！');
        }
        $order = Db::name('order')->where('order_sn',$order_sn)->find();
         if($order['shop_id'] != $user['shop_id'])
        {
            $this->error('非法操作');
        }
        if($order['orderstate'] == 1)
        {
            $this->error('已核销');
        }
        if($order['ground_id'] > 0 ){//如果是落地页订单
            $ground = Db::name('ground')->where('id',$order['ground_id'])->find();
            //落地页核销奖励
            if($ground['ground_score'] > 0){
                User::score($ground['ground_score'],$order['user_id'],'落地页核销奖');
            }
            $goods['market_price'] = 0;
        }else{
            $goods = Db::name('goods')->where('id',$order['goods_id'])->find();
        }

        $orders = Db::name('order')->where('order_sn',$order_sn)->update(['orderstate'=>1,'hx_time'=>time()]);
        if($orders != false)
        {
            //核销日志
            $data=['market_price'=>$goods['market_price'],'shop_id'=>$order['shop_id'],'user_id'=>$order['user_id'],'writeoff_id'=>$user['id'],'goods_name'=>$order['goods_name'],'price'=>$order['price'],'createtime'=>time(),'order_sn'=>$order_sn,'goods_image'=>$order['goods_image']];
            Db::name('writeoff_log')->insert($data);
            if($hxdiscount_id > 0 ) {//有核销优惠
                $hxdiscount = Db::name('hxdiscount')->where('id', $hxdiscount_id)->find();
                //落地页核销奖励
                if ($hxdiscount['duration'] > 0) {
                    User::score($hxdiscount['duration'], $order['user_id'], '购买商品核销奖励');
                }
            }
            $this->success('核销成功');
        }else{
            $this->error('核销失败');
        }
    }
    
    public function labellist()
    {
       $label =  Db::name('label')->order('weight desc')->select();
       $this->success('请求成功',$label);
    }
    public function actionsend(){
        $data['first']  = "恭喜";
        $data['course_name']  = "恭喜";
        $data['teacher_name']  = "恭喜";
        self::sendtemplate($data);
    }
    /**
     * @param $url_page
     * @param $url_scene
     * @return bool|string
     * 通过post方法发送公众号模板消息
     * {"access_token":"56_9T2rAZt02MKBh64zESeUha6YIlSLwrXZXFeCDpoQcAoe53RZ-t900sR71T4mdC7KoFwrLCEp6WQGzac90B2oHoMXaqGQYeHXfWbX_d50fmCzmgrNUn8xWxn-dC9032XP4tqZmtu9oNkdpS05NVEaAIAIQZ","expires_in":7200}
     */
    public function sendtemplate($data)
    {
        $config = get_addon_config('epay');
        $appid = $config['wechat']['g_app_id'];
        $secret =$config['wechat']['g_secret'];
        //$appid = "wx00e6c59afbd831d6";
        // $secret = "0512f5e03e31043ede5f8da14d0c32cc";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $weix = file_get_contents($url);//获得网页输出
        $obj=json_decode($weix,true);//解码
        $access_token= $obj['access_token'];//网页授权接口调用凭证
       // $access_token = "56_pGwWkQg_cOGaMfFi_Lz_MWOBFjYA4I8yPKfXJj1jfv0fZDIJ56-M-Pd0OccNjbHlicXbd8BvxsCphCgiBcV8NJMXQU_fhBvHhq4_ryUNYvrUPC5LvvNsqIbvaV3Kyjua7lSNlXByeziLwWwzNWUdAIAIRP";//网页授权接口调用凭证
        //$access_token = WeChatTrait::getAccessToken($appid, $secret);




        $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
        $uri = $uri.'?access_token='.$access_token;

        $data=  array('touser'=>'orJVtswOGNsv-5WkJhH_Pl9xtXcc',   //发给谁
            'template_id'=>'ChR2OdvLvZUx_L0OTH4Z4KFs2304JYWeNabtpJbGIrc',   //模板id
            'url'=>'#',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
            'topcolor'=>"#FF0000",   //颜色
            'miniprogram' => '',
            'data'=>array(

                'first'=>array(
                    'value'=>$data['first'],
                    'color'=>'#173177'
                ),
                'keyword1'=>array(
                    'value'=>$data['course_name'],
                    'color'=>'#173177'
                ),
                'keyword2'=>array(
                    'value'=>$data['teacher_name'],
                    'color'=>'#173177'
                ),
            )
        );
        $res_data = $this->getJson($uri,$data);
        $res_data = json_decode($res_data, true);
        if ($res_data['errcode'] != 0) {
            return false;
        }
        return true;


    }
    public function getJson($url = '', $param = [] ,$contentType = 'json'){
        $ch = curl_init();
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 请求参数类型
        $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // post提交
        if($param){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 执行并接收响应结果
        $output = curl_exec($ch);
        print_r($output);exit;
        // 关闭curl
        curl_close($ch);
        return $output !== false ? $output : false;

    }
    public function hxdiscount(){

        $shop_id = $this->request->post("shop_id");
        if(!$shop_id){
            $this->error("参数错误");
        }
        $cate = Db::name('hxdiscount')->where(['shop_id'=>$shop_id])->order('id desc')->field('id,duration')->select();

        $this->success('请求成功',$cate);
    }
    /**
     * 落地页
     */
    public function ground(){
       $shop_id = $this->request->post("shop_id");
        if(!$shop_id){
            $this->error("参数错误");
        }
        $collection= Db::name('shop')
            ->alias('s')
            ->join('ground g','s.id = g.shop_id')
            ->where('s.id',$shop_id)
            ->field('s.phone,s.shop_name,s.description,s.shop_images,s.business_times,s.endtime,s.logo,
            s.shop_address,g.ground_name,g.platform_introduce,g.image,g.yh_introduce,g.yh_name,g.id ground_id')
            ->find();
        $config = get_addon_config('alioss');
        if(!empty($collection['shop_images'])) {
            $im = explode(',', $collection['shop_images']);
            $collection['shop_images'] = $config['cdnurl'] . $im[0];
        }
        $collection['logo'] = $config['cdnurl'] . $collection['logo'];
        $collection['image'] = $config['cdnurl'] . $collection['image'];
        $this->success('请求成功',$collection);
    }
    public function qrCode(){
       /* $qrCode = new \Endroid\QrCode\QrCode();
        //$qrCode = new \Endroid\QrCode\QrCode();
        header('Content-Type: '.$qrCode->getContentType());
        $qrCode->save('qrcode.png');
        echo $qrCode->writeString();exit;
        $path = "/public/assets/img/qrcode";

        $prefix = "img_";//前缀可不写
        $output_file = $prefix.time().rand(100,999).'.jpg';
        $path = $path.$output_file;
        $r = file_put_contents($path, $qrCode->writeString());//返回的是字节数
        exit;*/
        //生成二维码 传生成二维码的文本内容
        $qrCode    = build('codeText');
        $qrCodeUrl =  serverUrl().'/assets/img/'.$qrCode;
        $this->success('返回成功', ['qrCodeUrl' => $qrCodeUrl]);
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 房东提交电表数据
     */
    public function electric(){
        $user_id=$this->auth->id;
        $device_id=$this->request->request('device_id');
        $strv=$this->request->request('strv');
        $endv=$this->request->request('endv');
        $price=$this->request->request('price');
        $img=$this->request->request('img');
        $ingv = $endv - $strv;
        $da_data = Db::name("device")->where('id',$device_id)->find();
        if(!$da_data){
            $this->error('设备ID错误');
        }
        $add_data['user_id'] =$user_id;
        $add_data['device_id'] =$device_id;
        $add_data['strv'] =$strv;
        $add_data['endv'] =$endv;
        $add_data['price'] =$price;
        $add_data['ingv'] = $ingv;
        $add_data['img'] = $img;
        $add_data['money'] = $ingv*$price;
        $add_data['createtime'] = time();
        if($ingv <= 0){
            $this->error('必须大于上次度数');exit;
        }
        $this_month=date('Y-m-01',strtotime(date('Y-m-d')));
        $this_one=strtotime($this_month);
        $this_five=strtotime($this_month)+86400*30;
        $is_upload=Db::name('electric')->where('createtime','between',[$this_one,$this_five])->where('device_id',$device_id)->find();//->where('status','in',[0,1])
        if ($is_upload) $this->error('每月只能上传一次');
        $res = Db::name('electric')->insert($add_data);
        if ($res) $this->success('成功');
        else $this->error('失败');
    }
    /**
     * 获取房东分类
     */
    public function getde(){
        $user_id=$this->auth->id;
        $data = Db::name('device')->where(['user_id'=>$user_id])->field('id,device_name,eleprice')->select();
        foreach ($data as $k=>$v){
            $ele = Db::name('electric')->where(['device_id'=>$v['id']])->order('id desc')->find();
            if($ele){
                $data[$k]['strv'] = $ele['endv'];
            }else{
                $data[$k]['strv'] = 0;
            }

        }
        $this->success('请求成功',$data);
    }
}
